package com.neusoft.mid.msf.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @program: pangu
 * @description: 日期工具类
 * @author: fengjd
 * @create: 2022-07-22 09:17
 **/
public class DateUtils {
    /** 时间格式(yyyy-MM-dd) */
    public final static String DATE_PATTERN = "yyyy-MM-dd";
    /** 时间格式(yyyy-MM-dd HH:mm:ss) */
    public final static String DATE_TIME_PATTERN = "yyyyMMddHHmmss";


    public static String format(Date date){
        return format(date, DATE_PATTERN);
    }

    /**
     * 格式化当前系统时间,返回14位时间戳
     * @return
     */
    public static String getCurrentDateTime(){
        return format(Calendar.getInstance().getTime(), DATE_TIME_PATTERN);
    }
    /**
     * 格式化当前系统时间,格式 yyyy-MM-dd
     * @return
     */
    public static String getCurrentDate(){
        return format(Calendar.getInstance().getTime(), DATE_PATTERN);
    }


    /**
     * 按指定格式,将日期对象转换成字符串
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern){
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return df.format(date);
        }
        return null;
    }

    /**
     * 将日期字符串从源格式,转换为目标格式
     * @param dateStr
     * @param srcParttern
     * @param dstPattern
     * @return
     */
    public static String changeFormat(String dateStr,String srcParttern ,String dstPattern){
        String ret= null;
        Calendar cal = parse(dateStr, srcParttern);
        if (cal!=null) {
            ret=format(cal.getTime(),dstPattern);
        }
        return ret;
    }

    public static Calendar parse(String dataStr,String pattern){
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        try {
            Date date = df.parse(dataStr);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            return cal;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;

    }
}
